<template>
  <div class="chat-app">
    <!-- 登录/加入房间区域 -->
    <div v-if="!joined" class="auth-section">
      <h1>WebSocket 聊天室</h1>
      <div class="auth-form">
        <input 
          v-model="username" 
          placeholder="输入用户名" 
          @keyup.enter="joinRoom"
        />
        <input 
          v-model="roomName" 
          placeholder="输入房间名" 
          @keyup.enter="joinRoom"
        />
        <button @click="joinRoom">加入聊天室</button>
      </div>
    </div>

    <!-- 聊天室主界面 -->
    <div v-else class="chat-container">
      <div class="chat-header">
        <h2>{{ roomName }} 聊天室</h2>
        <span class="user-count">在线用户: {{ userCount }}</span>
        <button @click="leaveRoom" class="leave-btn">离开房间</button>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.type]"
        >
          <span v-if="message.type === 'notification'" class="notification">
            {{ message.content }}
          </span>
          <template v-else>
            <span class="message-username" :style="{ color: message.color }">
              {{ message.username }}:
            </span>
            <span class="message-content">{{ message.content }}</span>
            <span class="message-time">{{ message.time }}</span>
          </template>
        </div>
      </div>

      <div class="chat-input">
        <input
          v-model="newMessage"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
          :disabled="!socketConnected"
        />
        <button 
          @click="sendMessage" 
          :disabled="!socketConnected || !newMessage.trim()"
        >
          发送
        </button>
      </div>

      <div v-if="!socketConnected" class="connection-status">
        连接已断开，正在尝试重新连接...
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import axios from 'axios'

// 状态管理
const username = ref('')
const roomName = ref('')
const joined = ref(false)
const newMessage = ref('')
const messages = ref([])
const messagesContainer = ref(null)
const socket = ref(null)
const socketConnected = ref(false)
const reconnectAttempts = ref(0)
const userCount = ref(0)
const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8']
const userColor = ref('')

// 加入房间
const joinRoom = async () => {
  if (!username.value.trim() || !roomName.value.trim()) {
    alert('请输入用户名和房间名')
    return
  }

  try {
    // 验证房间
    await axios.get(`http://localhost:8000/websocket/chat/${roomName.value}/`)
    
    // 分配用户颜色
    userColor.value = colors[Math.floor(Math.random() * colors.length)]
    
    // 连接WebSocket
    connectWebSocket()
    
    joined.value = true
    addSystemMessage(`欢迎 ${username.value} 加入聊天室`)
  } catch (error) {
    console.error('加入房间失败:', error)
    alert('加入房间失败，请稍后重试')
  }
}

// 离开房间
const leaveRoom = () => {
  if (socket.value) {
    socket.value.close()
  }
  joined.value = false
  messages.value = []
  username.value = ''
  roomName.value = ''
}

// 连接WebSocket
const connectWebSocket = () => {
  socket.value = new WebSocket(
    `ws://localhost:8000/ws/chat/${roomName.value}/?username=${encodeURIComponent(username.value)}`
  )

  socket.value.onopen = () => {
    socketConnected.value = true
    reconnectAttempts.value = 0
    console.log('WebSocket连接已建立')
  }

  socket.value.onmessage = (event) => {
    const data = JSON.parse(event.data)
    
    if (data.type === 'user_count') {
      userCount.value = data.count
    } else {
      messages.value.push({
        type: 'message',
        username: data.username,
        content: data.message,
        time: formatTime(new Date()),
        color: data.color || '#000'
      })
      scrollToBottom()
    }
  }

  socket.value.onclose = (event) => {
    socketConnected.value = false
    console.log('WebSocket连接关闭:', event)
    
    // 自动重连逻辑
    if (joined.value && reconnectAttempts.value < 5) {
      reconnectAttempts.value++
      const delay = Math.min(3000, reconnectAttempts.value * 1000)
      console.log(`尝试重新连接 (${reconnectAttempts.value}/5)`)
      setTimeout(connectWebSocket, delay)
    }
  }

  socket.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
  }
}

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim() || !socket.value || socket.value.readyState !== WebSocket.OPEN) {
    return
  }

  socket.value.send(
    JSON.stringify({
      message: newMessage.value,
      username: username.value,
      color: userColor.value
    })
  )
  
  newMessage.value = ''
}

// 添加系统消息
const addSystemMessage = (text) => {
  messages.value.push({
    type: 'notification',
    content: text
  })
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

// 组件卸载时关闭连接
onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close()
  }
})
</script>

<style scoped>
.chat-app {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.auth-section {
  text-align: center;
  margin-top: 50px;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
  max-width: 400px;
  margin: 30px auto;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.auth-form input {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.auth-form button {
  padding: 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.auth-form button:hover {
  background-color: #45a049;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background-color: #4CAF50;
  color: white;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.2rem;
}

.user-count {
  font-size: 0.9rem;
  opacity: 0.8;
}

.leave-btn {
  padding: 5px 10px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.leave-btn:hover {
  background-color: #d32f2f;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 15px;
  padding: 10px 15px;
  border-radius: 8px;
  line-height: 1.4;
  word-break: break-word;
}

.message.message {
  background-color: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.message.notification {
  text-align: center;
  color: #666;
  font-size: 0.9rem;
}

.notification {
  display: inline-block;
  padding: 5px 10px;
  background-color: #f0f0f0;
  border-radius: 4px;
}

.message-username {
  font-weight: bold;
  flex-shrink: 0;
}

.message-content {
  flex: 1;
}

.message-time {
  font-size: 0.8rem;
  color: #999;
  align-self: flex-end;
  flex-shrink: 0;
}

.chat-input {
  display: flex;
  padding: 15px;
  background-color: #eee;
  border-top: 1px solid #ddd;
}

.chat-input input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.chat-input button {
  padding: 12px 20px;
  margin-left: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.chat-input button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.chat-input button:not(:disabled):hover {
  background-color: #45a049;
}

.connection-status {
  padding: 10px;
  text-align: center;
  background-color: #fff3cd;
  color: #856404;
  font-size: 0.9rem;
}
</style>